
#!/bin/bash

# 参数配置
server_port=${1:-8000}
concurrent=${2:-10}
# 持续时间，格式可以是10s, 10m, 10h
duration=${3:"10m"}

# 请求目标URL
URL="http://localhost:$server_port/predict/system"
# 请求数据
POST_DATA='{"urls": ["https://sc01.alicdn.com/kf/S5bea4a1bd45e4edebf9ad9bc7843f46eF.jpg"]}'
# 请求数据保存到临时文件
echo "$POST_DATA" > payload.json

# 结果报告文件
REPORT_FILE="vegeta_report.txt"

# Vegeta攻击命令，并将其放在后台运行
echo "POST $URL" | vegeta attack \
    -rate=$concurrent \
    -duration=$duration \
    -timeout=10s \
    -body=payload.json \
    -header="Content-Type: application/json" > results.bin &

# Vegeta攻击的PID
ATTACK_PID=$!

# 实时输出进度和指标
echo "Starting real-time metrics..."
while kill -0 $ATTACK_PID 2> /dev/null; do
    clear && vegeta report -type=json < results.bin | jq 'if .latencies | length > 0 then . else empty end'
    sleep 2
done

# 等待攻击进程结束
wait $ATTACK_PID

# 删除临时文件
rm payload.json

# 生成最终报告
vegeta report -type=text < results.bin > $REPORT_FILE

# 输出最终报告
echo "Final report:"
cat $REPORT_FILE

# 清理
rm results.bin